//
//  LBOauthViewController.swift
//  LBNewWeiBo
//
//  Created by bin on 15/10/29.
//  Copyright © 2015年 bin. All rights reserved.
//

import UIKit
import SVProgressHUD
class LBOauthViewController: UIViewController {
    
    override func loadView() {
        
        // 将控制器的视图变更为网页视图
        view = webView
        
        // 设置代理
        webView.delegate = self
        
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        // 导航右边的取消按钮
        self.navigationItem.rightBarButtonItem = UIBarButtonItem(title: "取消", style: UIBarButtonItemStyle.Plain, target: self, action: "close")
        // 填充账号
            navigationItem.leftBarButtonItem = UIBarButtonItem(title: "填充", style: UIBarButtonItemStyle.Plain, target: self, action: "autoFill")
        
        
        // 加载网页信息
        let request = NSURLRequest(URL: LBNetworkTools.sharedInstance.oauthRUL()) // 请求
        webView.loadRequest(request) // 加载
        
    }
    
    /// 自动填充账号密码
    func autoFill() {
        let js = "document.getElementById('userId').value='18666636172';" + "document.getElementById('passwd').value='liubin910721';"
        
        // webView执行js代码
        webView.stringByEvaluatingJavaScriptFromString(js)
    }
    
    /// 关闭控制器
     func close() {
       SVProgressHUD.dismiss()
        dismissViewControllerAnimated(true, completion:nil)
    }
    
    //MARK: -懒加载
    /// 网络视图的懒加载
   private lazy var webView = UIWebView()
    
}


//MARK: - 扩展  LBOauthViewController 代理协议实现 UIWebViewDelegate

/*
optional public func webViewDidStartLoad(webView: UIWebView)
optional public func webViewDidFinishLoad(webView: UIWebView)
*/
extension LBOauthViewController : UIWebViewDelegate {
    
    /// 开始加载请求
    func  webViewDidStartLoad(webView: UIWebView) {
        // 开始请求
        SVProgressHUD.showWithStatus("正在狂命加载", maskType: SVProgressHUDMaskType.Black)
    }
    
    /// 加载请求完毕
    func webViewDidFinishLoad(webView: UIWebView) {
        
        /// 请求完毕
        SVProgressHUD.dismiss()
    }
    
    /// 询问是否加载 request
    func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool {
        
        let urlString = request.URL!.absoluteString
        print("urlString:\(urlString)")
        
        // 加载的不是回调地址
        if !urlString.hasPrefix(LBNetworkTools.sharedInstance.redirect_uri){
            // 可以加载
            return true
        }
        
        if let query = request.URL?.query {
            print("query\(query)")
            
            let codeString = "code="
            
            if query.hasPrefix(codeString){
                // 确定
                // code=
                // 转成NNString
                let nsQuery = query as NSString
                
                // 截取code的值
                
                let code = nsQuery.substringFromIndex(codeString.characters.count)
                //print("code: \(code)")
                
                // 获取access: token
                loadAccessToken(code)
            } else{
                // 取消
                self.close()
            }
            
        }
        
        return false
    }
    
    /// 调用网络工具类去加载 access token
    func loadAccessToken(code: String) {
        
        LBNetworkTools.sharedInstance.loadAccessToKen(code) { (result, error) -> () in
            // 判断请求是否出错 或 请求内容是为空
            if error != nil || result == nil {

                self.netError("网络不给力")
                return
                
            }
            
            print("result: \(result)")
            let account = LBUserAccout(dict: result!)
            
            print("\(account)")
            // 保存沙盒
            account.saveAccount()
            
            account.loadUserInfo({ (error) -> () in
                if error != nil {
                    // 加载数据出错
                    self.netError("加载数据出错")
                    return
                }
                //print("account:\(LBUserAccout.loadAccount())")
                self.close()
                // 切换控制器
                (UIApplication.sharedApplication().delegate as! AppDelegate).switchRootController(false)
             })
        }
    }
    
    /// 错误提示
    private func netError(message: String) {
        SVProgressHUD.showErrorWithStatus(message, maskType: SVProgressHUDMaskType.Black)
        
        // 延迟关闭
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (Int64)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), { () -> Void in
            self.close()
        })
    }
    
    
    
    
}














